// ignore_for_file: must_be_immutable, constant_identifier_names, non_constant_identifier_names, prefer_typing_uninitialized_variables

/*
 * @Author: CodeHare
 * @Date: 2023-10-30 10:48:14
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-23 17:53:59
 * @Description: EMS参数设置之系统设置
 */
// ignore_for_file: file_names

import 'dart:async';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/ems_params_setting_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/system_set_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_set_interface.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';
import '../../../../../../../../components/log_utils.dart';

class SystemSettingWidget extends StatefulWidget {
  /// 设备ID
  String deviceId;

  /// 角色
  int currentRole;

  SystemSettingWidget(this.deviceId, this.currentRole, {super.key});

  @override
  State<SystemSettingWidget> createState() => _SystemSettingWidgetState();
}

class _SystemSettingWidgetState extends State<SystemSettingWidget> {
  EmsParamsSettingController paramsSetController =
      Get.find<EmsParamsSettingController>();
  var systemEnableSetList = SystemEnableSetModel().systemEnableSetList;
  var systemTimingSetList = SystemEnableSetModel().systemTimingSetList;
  var gridParamsSettingList = SystemEnableSetModel().gridParamsSettingList;

  /// 使能禁用常量
  final String ENABLED = ResKey.thingsEnable.tr; // "使能";
  final String FORBIDDEN = ResKey.thingsDisable.tr; // "禁用";
  final String SELECTENABLEDSTATUS = ResKey.deviceEnableSettings.tr;

  /// 系统使能设置请求参数
  late SettingReqParams requestParams;
  late Map<String, dynamic> sysEnableInput = {
    "SysEnableSelfStartFunction": "",
    "MunicipalChargingFunctionEnabled": "",
    "EnableOffGridOperationFunction": "",
    "EnableGridConnectionFunction": "",
  };

  ///电网参数设置请求参数
  late Map<String, dynamic> powerGridInput = {
    "antiBackflowThreshold": "",
    "maximumLoadOfTransformer": "",
  };

  /// 系统校时设置请求参数
  late Map<String, dynamic> sysTimingInput = {
    "correctionTime": "",
  };

  /// 激活模块
  bool editEnabled = false;
  bool editTiming = false;
  bool editPowerGrid = false;
  bool activeSubmit = false;

  /// 弹窗相关
  String hintText = "";
  int selectedIndex = 0;
  var conditions = <String>[
    ResKey.thingsEnable.tr,
    ResKey.thingsDisable.tr,
  ];

  /// 允许下发指令
  bool allowSend = false;

  /// 时间选择器
  String timePickerTitle = "";
  String format =
      'yyyy${ResKey.year},MM${ResKey.month.tr},dd${ResKey.day},HH${ResKey.hour},mm${ResKey.minute}';

  String MIN_DATETIME = '1999-01-15 00:00:00';
  String MAX_DATETIME = '2100-12-31 23:59:59';

  var separatorBuilder = (BuildContext context, int index) => Divider(
        color: Colour.dividerColor,
        height: 1,
        indent: 16.w,
        endIndent: 16.w,
      );

  /// 网络状态
  ConnectStatusType? connectStatus = ConnectStatusType.off;

  /// 订阅在线状态数据流
  UseSubsribe emsOnlineStatusSubsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsOnlineStatusSubscription;
  late Stream<Map<String, dynamic>> emsOnlineStatusBroadcastStream;

  /// 订阅指令值数据流
  UseSubsribe emsValSubscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsValSubscription;
  late Stream<Map<String, dynamic>> emsValBroadcastStream;
  late Map socketMap = {};

  @override
  void initState() {
    super.initState();

    _listenEmsOnlineStatusValue();
    _listenEmsControlValue();
    _initSysEnabledList();
    _initPowerGridList();
    _initSysTimingList();
  }

  /// 监听EMS设备在线状态
  void _listenEmsOnlineStatusValue() {
    emsOnlineStatusBroadcastStream = emsOnlineStatusSubsribe
        .start([int.parse(widget.deviceId)], true,
            type: MessageEventType.networkStatus)
        .stream
        .asBroadcastStream();

    emsOnlineStatusSubscription = emsOnlineStatusBroadcastStream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
          $ConnectStatusTypeEnumMap,
          data['networkStatus'],
        );
      }
    });
  }

  /// 监听EMS指令值
  void _listenEmsControlValue() {
    emsValBroadcastStream = emsValSubscribe
        .start([int.parse(widget.deviceId)], true)
        .stream
        .asBroadcastStream();
    showLoading(toast: ResKey.loading.tr);

    emsValSubscription = emsValBroadcastStream.listen(
      (data) {
        socketMap = data;
        if (editEnabled || editTiming || editPowerGrid) return;
        Log.d("系统使能编辑====$editEnabled，系统校时编辑=====$editTiming");

        socketMap.forEach(
          (key, value) {
            String originData = value.toString();

            /// 【系统使能模块】
            if (key == 'SysEnableSelfStartFunction') {
              Log.d("====查看值====$key====$originData");
              if (originData == "0") {
                systemEnableSetList[1].previousValue =
                    systemEnableSetList[1].value = ENABLED;
              } else if (originData == "1") {
                systemEnableSetList[1].previousValue =
                    systemEnableSetList[1].value = FORBIDDEN;
              } else {
                systemEnableSetList[1].previousValue =
                    systemEnableSetList[1].value = "--";
              }
            } else if (key == 'MunicipalChargingFunctionEnabled') {
              Log.d("====查看值====$key====$originData");
              if (originData == "0") {
                systemEnableSetList[2].previousValue =
                    systemEnableSetList[2].value = ENABLED;
              } else if (originData == "1") {
                systemEnableSetList[2].previousValue =
                    systemEnableSetList[2].value = FORBIDDEN;
              } else {
                systemEnableSetList[2].previousValue =
                    systemEnableSetList[2].value = "--";
              }
            } else if (key == 'EnableOffGridOperationFunction') {
              Log.d("====查看值====$key====$originData");
              if (originData == "0") {
                systemEnableSetList[3].previousValue =
                    systemEnableSetList[3].value = ENABLED;
              } else if (originData == "1") {
                systemEnableSetList[3].previousValue =
                    systemEnableSetList[3].value = FORBIDDEN;
              } else {
                systemEnableSetList[3].previousValue =
                    systemEnableSetList[3].value = "--";
              }
            } else if (key == 'EnableGridConnectionFunction') {
              Log.d("====查看值====$key====$originData");
              if (originData == "0") {
                systemEnableSetList[4].previousValue =
                    systemEnableSetList[4].value = ENABLED;
              } else if (originData == "1") {
                systemEnableSetList[4].previousValue =
                    systemEnableSetList[4].value = FORBIDDEN;
              } else {
                systemEnableSetList[4].previousValue =
                    systemEnableSetList[4].value = "--";
              }

              /// 【电网参数模块】
            } else if (key == 'antiBackflowThreshold') {
              Log.d("===$key的具体值====$originData");

              gridParamsSettingList[1].value = gridParamsSettingList[1]
                  .textEditingController!
                  .text = originData.toString();
            } else if (key == 'maximumLoadOfTransformer') {
              Log.d("===$key的具体值====$originData");

              gridParamsSettingList[2].value = gridParamsSettingList[2]
                  .textEditingController!
                  .text = originData.toString();

              /// 【系统校时模块】
            } else if (key == 'correctionTime') {
              Log.d("====查看值====$key====$originData");

              /// 常见的时间戳有两种：Unix时间戳和Windows时间戳。   - 10位或13位
              /// Unix时间戳表示的是自1970年1月1日0时0分0秒UTC（协调世界时）起至现在的秒数，以整数形式存储；
              /// Windows时间戳则表示的是自1601年1月1日0时0分0秒UTC起至现在的100纳秒数，以整数形式存储。
              /// || (originData.length != 10 && originData.length != 13)
              if (originData.isEmpty) {
                systemTimingSetList[1].previousValue =
                    systemTimingSetList[1].value = "";
              } else {
                if (originData.contains('.')) {
                  originData = originData.split('.')[0];
                }

                var timeStamp = int.parse(originData);
                try {
                  systemTimingSetList[1].previousValue =
                      systemTimingSetList[1].value =
                          DateTime.fromMillisecondsSinceEpoch(timeStamp)
                              .toString()
                              .split('.')[0];
                } catch (err) {
                  showError(err);
                  systemTimingSetList[1].previousValue =
                      systemTimingSetList[1].value = "";
                }
              }
            }
          },
        );

        dismissLoading();
        setState(() {});
      },
    );
  }

  /// 初始化使能参数值
  void _initSysEnabledList() {
    var length = systemEnableSetList.length;
    for (var i = 1; i < length; i++) {
      systemEnableSetList[i].previousValue =
          systemEnableSetList[i].value = "--";
    }
    // systemEnableSetList[1].previousValue = systemEnableSetList[1].value = "--";
    // systemEnableSetList[2].previousValue = systemEnableSetList[2].value = "--";
    // systemEnableSetList[3].previousValue = systemEnableSetList[3].value = "--";
    // systemEnableSetList[4].previousValue = systemEnableSetList[4].value = "--";
  }

  /// 初始化电网参数值
  void _initPowerGridList() {
    var length = gridParamsSettingList.length;
    for (var i = 1; i < length; i++) {
      gridParamsSettingList[i].value =
          gridParamsSettingList[i].textEditingController!.text = "--";
    }
    // gridParamsSettingList[1].value =
    //     gridParamsSettingList[1].textEditingController!.text = "--";

    // gridParamsSettingList[2].value =
    //     gridParamsSettingList[2].textEditingController!.text = "--";
  }

  /// 初始化系统校时参数值
  void _initSysTimingList() {
    systemTimingSetList[1].previousValue = systemTimingSetList[1].value = "--";
  }

  /// 点击参数配置
  void _clickParamsSetting(index) {
    if (connectStatus == ConnectStatusType.off) return;
    activeSubmit = true;

    if (index == 0) {
      editEnabled = true;
      editPowerGrid = false;
      editTiming = false;

      for (var i = 1; i < systemEnableSetList.length; i++) {
        EnableItemModel item = systemEnableSetList[i];
        if (item.value == "--") {
          item.value = ResKey.pleSelect.tr;
        }
      }
    } else if (index == 1) {
      editEnabled = false;
      editPowerGrid = true;
      editTiming = false;

      for (var i = 1; i < gridParamsSettingList.length; i++) {
        GridParameterItem item = gridParamsSettingList[i];
        if (item.textEditingController!.text == "--") {
          item.textEditingController!.text = "";
        }
      }
    } else {
      editEnabled = false;
      editPowerGrid = false;
      editTiming = true;

      if (systemTimingSetList[1].value == "--") {
        systemTimingSetList[1].value = ResKey.pleSelect.tr;
      }
    }
    setState(() {});
  }

  /// 展示隐藏下发参数按钮
  void _showHiddenButton() {
    activeSubmit = false;
    editEnabled = false;
    editPowerGrid = false;
    editTiming = false;
    setState(() {});
  }

  /// 下发失败撤销赋值参数
  void _restoreSystemEnableSetList() {
    for (var i = 1; i < systemEnableSetList.length; i++) {
      systemEnableSetList[i].value = systemEnableSetList[i].previousValue;
    }
    // systemEnableSetList[1].value = systemEnableSetList[1].previousValue;
    // systemEnableSetList[2].value = systemEnableSetList[2].previousValue;
    // systemEnableSetList[3].value = systemEnableSetList[3].previousValue;
    // systemEnableSetList[4].value = systemEnableSetList[4].previousValue;
    setState(() {});
  }

  /// 下发失败撤销赋值参数
  _restoreGridParamsSettingList() {
    for (var i = 1; i < gridParamsSettingList.length; i++) {
      gridParamsSettingList[i].textEditingController!.text =
          gridParamsSettingList[i].value;
    }
    // gridParamsSettingList[1].textEditingController!.text =
    //     gridParamsSettingList[1].value;
    // gridParamsSettingList[2].textEditingController!.text =
    //     gridParamsSettingList[2].value;
    setState(() {});
  }

  /// 下发失败撤销赋值参数
  void _restoreSystemTimingSetList() {
    for (var i = 1; i < systemTimingSetList.length; i++) {
      systemTimingSetList[i].value = systemTimingSetList[i].previousValue;
    }
    // systemTimingSetList[1].value = systemTimingSetList[1].previousValue;
    setState(() {});
  }

  /// 使能禁用值的转化
  String _formatEnabledSetValue(String value) => value == ENABLED ? "0" : "1";

  /// 赋值系统使能当前选择参数
  void _assignEnabledInstructParams() {
    sysEnableInput['SysEnableSelfStartFunction'] =
        _formatEnabledSetValue(systemEnableSetList[1].value);

    sysEnableInput['MunicipalChargingFunctionEnabled'] =
        _formatEnabledSetValue(systemEnableSetList[2].value);

    sysEnableInput['EnableOffGridOperationFunction'] =
        _formatEnabledSetValue(systemEnableSetList[3].value);

    sysEnableInput['EnableGridConnectionFunction'] =
        _formatEnabledSetValue(systemEnableSetList[4].value);
  }

  double _formatPowerGridValue(String value) => double.parse(value);

  /// 赋值系统校时间当前选择参数
  void _assignPowerGridInstructParams() {
    powerGridInput['antiBackflowThreshold'] = _formatPowerGridValue(
        gridParamsSettingList[1].textEditingController!.text);

    powerGridInput['maximumLoadOfTransformer'] = _formatPowerGridValue(
        gridParamsSettingList[2].textEditingController!.text);
  }

  /// 赋值系统校时间当前选择参数
  void _assignTimingInstructParams() {
    var timeStamp =
        DateTime.parse(systemTimingSetList[1].value).millisecondsSinceEpoch;

    /// 接口需要的是 10位数的时间戳
    sysTimingInput['correctionTime'] = int.parse(
      timeStamp.toString().substring(0, 13),
    );
  }

  /// 风冷EMS系统使能设置接口参数 Enabling settings for air-cooled EMS system
  Map<String, dynamic>? _collectInstructParams(int type) {
    requestParams = SettingReqParams(deviceId: widget.deviceId, input: null);

    switch (type) {
      case 0:
        requestParams.input = sysEnableInput;
        return SettingSysEnable().trigger(widget.deviceId, requestParams);

      case 1:
        requestParams.input = powerGridInput;
        return ConverterGridParameterSettings()
            .trigger(widget.deviceId, requestParams);

      default:
        requestParams.input = sysTimingInput;
        return CorrectionTime().trigger(widget.deviceId, requestParams);
    }
  }

  /// 表单校验
  void _validate(list) {
    if (editPowerGrid) {
      for (var i = 1; i < 3; i++) {
        if (list[i].textEditingController.text.isEmpty) {
          allowSend = false;
          return;
        } else {
          allowSend = true;
        }
      }
    } else {
      // ignore: avoid_function_literals_in_foreach_calls
      for (var i = 1; i < list.length; i++) {
        if (list[i].value.isEmpty ||
            list[i].value == ResKey.pleSelect.tr ||
            list[i].value == "--") {
          allowSend = false;
          return;
        } else {
          allowSend = true;
        }
      }
    }

    setState(() {});
  }

  /// 表单校验失败
  void _validateFailure() {
    showError('请填写所有必填选项');
  }

  void _cancelEdit() {
    if (editEnabled) {
      _restoreSystemEnableSetList();
    } else if (editPowerGrid) {
      _restoreGridParamsSettingList();
    } else {
      _restoreSystemTimingSetList();
    }
  }

  void _setFail(int index) {
    switch (index) {
      case 0:
        _restoreSystemEnableSetList();
        return;
      case 1:
        _restoreGridParamsSettingList();
        return;
      case 2:
        _restoreSystemTimingSetList();
        return;
    }
  }

  /// 确认参数下发警告框
  void _showConfirmSendDialog() {
    BrnDialogManager.showConfirmDialog(
      context,
      title: 'siteMonitor.issueParameters'.tr, // "参数下发",
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      message: ResKey.deviceWhetherExecuteCurrentParameter.tr, //"是否执行当前参数下发",
      onConfirm: () {
        var params;
        int curIndex;

        /// 参数
        if (allowSend) {
          if (editEnabled) {
            _assignEnabledInstructParams();
            params = _collectInstructParams(0);
            curIndex = 0;
          } else if (editPowerGrid) {
            _assignPowerGridInstructParams();
            params = _collectInstructParams(1);
            curIndex = 1;
          } else {
            _assignTimingInstructParams();
            params = _collectInstructParams(2);
            curIndex = 2;
          }

          Get.back();
          paramsSetController.sendCommand(context, params).then((value) {
            if (!paramsSetController.commandExecutionSuccessful) {
              _setFail(curIndex);
            }
          });

          _showHiddenButton();
        }
      },
      onCancel: () {
        Get.back();
        _cancelEdit();
        _showHiddenButton();
      },
    );
  }

  /// 选择时间选择器
  void _showDatePicker(context) {
    BrnDatePicker.showDatePicker(
      context,
      canBarrierDismissible: true,
      initialDateTime: DateTime.now(),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      minDateTime: DateTime.parse(MIN_DATETIME),
      dateFormat: format,
      pickerMode: BrnDateTimePickerMode.datetime,
      rootNavigator: true,
      pickerTitleConfig: BrnPickerTitleConfig(
        cancel: Text(
          ResKey.cancel.tr,
          style: TextStyle(
            color: Colour.lightTextColor,
            fontSize: 14.sp,
          ),
        ),
        confirm: Text(
          ResKey.finished.tr,
          style: TextStyle(
            color: Colour.primaryColor,
            fontSize: 14.sp,
          ),
        ),
        titleContent: timePickerTitle,
      ),
      onConfirm: (dateTime, list) {
        activeSubmit = true;
        systemTimingSetList[1].value = dateTime.toString().substring(0, 16);
        timePickerTitle = systemTimingSetList[1].value;
        setState(() {});
      },
      onClose: () {
        activeSubmit = true;
        setState(() {});
      },
    );
  }

  /// 使能弹窗展示
  void _showEnabledDialog(context, item, index) {
    showDialog(
      context: context,
      builder: (_) => StatefulBuilder(
        builder: (context, state) {
          if (systemEnableSetList[index].value == ENABLED) {
            selectedIndex = 0;
          } else {
            selectedIndex = 1;
          }

          return BrnSingleSelectDialog(
            isClose: true,
            title: SELECTENABLEDSTATUS,
            conditions: conditions,
            checkedItem: conditions[selectedIndex],
            submitText: ResKey.confirm.tr,
            onItemClick: (BuildContext context, int index) {
              hintText = conditions[index];
              selectedIndex = index;
            },
            onSubmitClick: (data) {
              setState(() {
                systemEnableSetList[index].value = conditions[selectedIndex];
              });
            },
          );
        },
      ),
    );
  }

  /// 生成表单表头
  Container _generateListHeader(item, int moduleIndex) {
    return Container(
      height: 53,
      padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),
      alignment: Alignment.center,
      color: Colour.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            item.label,
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.w600),
          ),
          GestureDetector(
            onTap: () => _clickParamsSetting(moduleIndex),
            child: Text(
              editEnabled || editTiming || editPowerGrid ? "" : item.value,
              style: TextStyle(
                  fontSize: 14.sp,
                  color: Colour.primaryColor,
                  fontWeight: FontWeight.w400),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<EmsParamsSettingController>(
      builder: (_) => Scaffold(
        body: Column(
          children: <Widget>[
            _createSysEnabled(),
            _createGridParams(),
            _createSystemTime(),
            _createSubmitBtn(),
          ],
        ),
      ),
    );
  }

  /// 系统使能设置 (业主不展示)
  Widget _createSysEnabled() {
    return Visibility(
      visible: !editTiming &&
          !editPowerGrid &&
          widget.currentRole != RoleType.owner.value,
      child: Container(
        height: 263,
        margin: const EdgeInsets.only(top: 10),
        child: ListView.separated(
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          itemBuilder: (context, index) {
            final item = systemEnableSetList[index];

            if (index == 0) {
              return _generateListHeader(item, 0);
            }

            return GestureDetector(
              onTap: () {
                if (editEnabled) {
                  _showEnabledDialog(context, item, index);
                }
              },
              child: Container(
                height: 50,
                padding: EdgeInsets.only(
                  left: editEnabled ? 6.w : 16.w,
                  right: 16.w,
                ),
                color: Colour.white,
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Visibility(
                      visible: editEnabled,
                      child: Padding(
                        padding: EdgeInsets.only(
                          right: 2.w,
                        ),
                        child: Text(
                          "*",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colour.warningTextColor,
                            fontSize: 14.sp,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Text(
                        item.label,
                        style: TextStyle(
                          color: Colour.lightTextColor,
                          fontSize: 14.sp,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(right: 7.w),
                            child: Text(
                              textAlign: TextAlign.end,
                              item.value.isEmpty ? "" : item.value,
                              style: TextStyle(
                                color: connectStatus == ConnectStatusType.off
                                    ? Colour.hintTextColor
                                    : Colour.mainTextColor,
                              ),
                            ),
                          ),
                          Visibility(
                            visible: editEnabled,
                            child: Icon(
                              Icons.arrow_forward_ios,
                              size: 12.sp,
                              color: Colour.hintTextColor,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
          separatorBuilder: separatorBuilder,
          itemCount: systemEnableSetList.length,
        ),
      ),
    );
  }

  /// 电网参数设置
  Widget _createGridParams() {
    return Visibility(
        visible: !editEnabled &&
            !editTiming &&
            widget.currentRole != RoleType.owner.value,
        child: Container(
          margin: const EdgeInsets.only(top: 10),
          height: 153,
          child: ListView.separated(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              final item = gridParamsSettingList[index];

              if (index == 0) {
                return _generateListHeader(item, 1);
              } else {
                return Container(
                  color: Colour.white,
                  child: ItemWidget(
                    item.label,
                    item.textEditingController,
                    isRequired: editPowerGrid,
                    isCanEdit: editPowerGrid,
                    unitString: item.unit,
                    hintString: editPowerGrid ? ResKey.plsInput.tr : '',
                    titleColor: Colour.lightTextColor,
                    unitTextColor: connectStatus == ConnectStatusType.off
                        ? Colour.offlineTextColor
                        : Colour.mainTextColor,
                    inputTextColor: connectStatus == ConnectStatusType.off
                        ? Colour.offlineTextColor
                        : Colour.mainTextColor,
                    titleFont: 14,
                    isShowDivider: false,
                  ),
                );
              }
            },
            separatorBuilder: separatorBuilder,
            itemCount: gridParamsSettingList.length,
          ),
        ));
  }

  /// 系统校时设置
  Widget _createSystemTime() {
    return Visibility(
      visible: !editEnabled && !editPowerGrid,
      child: Container(
        height: 113,
        margin: const EdgeInsets.only(top: 10),
        child: ListView.separated(
            physics: const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            itemBuilder: (context, index) {
              final item = systemTimingSetList[index];

              if (index == 0) {
                return _generateListHeader(item, 2);
              }

              return GestureDetector(
                onTap: () {
                  if (editTiming) {
                    setState(() {
                      activeSubmit = false;
                    });

                    _showDatePicker(Get.context);
                  }
                },
                child: Container(
                  height: 50,
                  padding: EdgeInsets.only(
                    left: editTiming ? 6.w : 16.w,
                    right: 16.w,
                  ),
                  color: Colour.white,
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Visibility(
                        visible: editTiming,
                        child: Padding(
                          padding: EdgeInsets.only(
                            right: 2.w,
                          ),
                          child: Text(
                            "*",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: Colour.warningTextColor,
                              fontSize: 14.sp,
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Text(
                          item.label,
                          style: TextStyle(
                            color: Colour.lightTextColor,
                            fontSize: 14.sp,
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 2,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(right: 7.w),
                              child: Text(
                                textAlign: TextAlign.end,
                                item.value.isEmpty ? "" : item.value,
                                style: TextStyle(
                                  color: connectStatus == ConnectStatusType.off
                                      ? Colour.hintTextColor
                                      : Colour.mainTextColor,
                                ),
                              ),
                            ),
                            Visibility(
                              visible: editTiming,
                              child: Icon(
                                Icons.arrow_forward_ios,
                                size: 12.sp,
                                color: Colour.hintTextColor,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
            separatorBuilder: separatorBuilder,
            itemCount: systemTimingSetList.length),
      ),
    );
  }

  /// 下发按钮取消按钮
  Widget _createSubmitBtn() {
    return Visibility(
      visible: activeSubmit,
      child: Expanded(
        child: Align(
          alignment: Alignment.bottomCenter,
          child: YtBrnBottomButtonPanel(
            mainButtonName: ResKey.deviceSendCommand.tr,
            mainButtonOnTap: () {
              if (editEnabled) {
                _validate(systemEnableSetList);
              } else if (editPowerGrid) {
                _validate(gridParamsSettingList);
              } else {
                _validate(systemTimingSetList);
              }

              allowSend ? _showConfirmSendDialog() : _validateFailure();
            },
            secondaryButtonName: ResKey.cancel.tr,
            secondaryButtonBorder: Border.all(
              color: Colour.dividerColor,
            ),
            secondaryButtonOnTap: () {
              _cancelEdit();
              _showHiddenButton();
            },
          ),
        ),
      ),
    );
  }

  @override
  dispose() {
    emsOnlineStatusSubscription?.cancel();
    emsOnlineStatusSubsribe.closeListen();
    emsValSubscription?.cancel();
    emsValSubscribe.closeListen();

    super.dispose();
  }
}
